package com.nd.android.u.ui.activity.chat_relative_image;

import java.util.ArrayList;

import uk.co.senab.photoview.PhotoView;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.allCommon.CommUtil;
import com.common.allCommon.TextHelper;
import com.common.android.ui.gif.GifImageView;
import com.common.android.ui.widget.CompatibleViewPager;
import com.common.android.utils.ImageUtils;
import com.nd.android.u.allCommonUtils.ToastUtils;
import com.nd.android.u.ui.ChatEntry;
import com.nd.android.u.ui.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.product.android.business.Const;
import com.product.android.ui.activity.BaseReceiveActivity;
import com.product.android.ui.imageHolder.CircleProgress;
import com.product.android.ui.imageHolder.PictureHolder;
import com.product.android.utils.SaveTweetImageTask;

public class ShowImagesActivity extends BaseReceiveActivity {
	private CompatibleViewPager viewPager;
	private ArrayList<String> urlList;
	private int currentPosition;
	private TextView tvPosition;
	private boolean mIsFromChat=false;
	private ArrayList<GifImageView> mGifImageViews=new ArrayList<GifImageView>();
	private ArrayList<String> mThumbList;
	private Bitmap mThumbnail;
//	public DisplayImageOptions mChatImageOptions = null;
//	private final String HEAD_DISC_CACHE_DIR = "head";
//	private final int DISC_CACHE_SIZE_64MB = 64 * 1024 * 1024;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getIntent().getExtras();
		if(bundle.containsKey(Const.BUNDLE_KEY.URL_LIST)){
			urlList = bundle.getStringArrayList(Const.BUNDLE_KEY.URL_LIST);
		}
		if (urlList == null || urlList.isEmpty()) {
			finish();
			return;
		}
		if(bundle.containsKey(Const.BUNDLE_KEY.THUMB_LIST)){
			mThumbList = bundle.getStringArrayList(Const.BUNDLE_KEY.THUMB_LIST);
		}
		mIsFromChat=bundle.getBoolean("chat");
		initComponent();
	}

	private void initComponent() {
		setContentView(R.layout.activity_show_images);
		viewPager = (CompatibleViewPager) findViewById(R.id.viewpager);
		findViewById(R.id.ibtn_save).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				doSave(currentPosition);				
			}
		});
		tvPosition = (TextView) findViewById(R.id.tv_position);
		tvPosition.setText(1 + "/" + urlList.size());
		tvPosition.setVisibility(urlList.size() > 1 ? View.VISIBLE : View.GONE);
		viewPager.setAdapter(new PagerAdapter() {
			
			@Override
			public boolean isViewFromObject(View view, Object object) {
				return view == object;
			}
			
			@Override
			public int getCount() {
				return urlList.size();
			}
			
			@Override
		    public int getItemPosition(Object object) {
		        return POSITION_NONE;
		    }
			
			@TargetApi(Build.VERSION_CODES.CUPCAKE)
			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				final PictureHolder mHolder = new PictureHolder();
				View view = getLayoutInflater().inflate(
						R.layout.fragment_picture_flow_item, null);
				mHolder.rlProgress = (RelativeLayout) view.findViewById(R.id.rlProgress);
				mHolder.cpProgress = (CircleProgress) view.findViewById(R.id.cpProgress);
				mHolder.gifPicture=(GifImageView)view.findViewById(R.id.gifPicture);
				mHolder.ivPicture = (PhotoView) view.findViewById(R.id.ivPicture);
				mHolder.leftBtn = (Button) view.findViewById(R.id.leftBtn);
				mHolder.leftBtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bottom_left_save, 0, 0, 0);
				mHolder.rightBtn = (Button) view.findViewById(R.id.rightBtn);
				mHolder.rightBtn.setVisibility(View.GONE);
				mHolder.leftBtn.setVisibility(View.GONE);
				mHolder.registerEvent();
				view.setTag(mHolder);
				String url= urlList.get(position);
				mHolder.gifPicture.setSaveFrames();
				if (mThumbList!=null){
					//存在缩略图
					String thumb=mThumbList.get(position);
					if (TextHelper.isUrl(url)){
						//缩略图是个URL
//						ImageLoader.getInstance().displayImage(thumb, url, mHolder.ivPicture,ChatEntry.INSTANCE.chatOptions);
						if (mIsFromChat && CommUtil.isGifPicture(url)){
							//如果是聊天界面过来的且是GIF图片,要用SHOWIMAGE方法
							mHolder.showImage(thumb, url, ChatEntry.INSTANCE.chatOptions);	
							mGifImageViews.add(mHolder.gifPicture);
						}else{
//							mHolder.ivPicture.setImageBitmap(ImageLoader.getInstance().findCachedBitmapForImageUri(thumb));
							mHolder.showImage(thumb,url, ChatEntry.INSTANCE.chatOptions);
						}
					}else{
						//本地上传的图片
						if (ImageLoader.getInstance().findCachedBitmapForImageUri(thumb)==null){
							mThumbnail=BitmapFactory.decodeFile(thumb.substring(7));
							if (mThumbnail!=null){
								mHolder.ivPicture.setImageBitmap(mThumbnail);
							}
						}else{
							mHolder.ivPicture.setImageBitmap(ImageLoader.getInstance().findCachedBitmapForImageUri(thumb));
						}
						ImageLoader.getInstance().displayImage(url, mHolder.ivPicture);
					}
				}else{
					
					String path = ImageLoader.getInstance().getDiscCacheFileAbsPath(
		                    ChatEntry.INSTANCE.chatOptions, url);
					
					if (mIsFromChat && (ImageUtils.isGifFile(path) || CommUtil.isGifPicture(url))){
						//如果是聊天界面过来的且是GIF图片,要用SHOWIMAGE方法
						mHolder.showImage(url+"&thumb=120", url, ChatEntry.INSTANCE.chatOptions);	
						mGifImageViews.add(mHolder.gifPicture);
					}else{
						ImageLoader.getInstance().displayImage(url, mHolder.ivPicture,ChatEntry.INSTANCE.chatOptions);
					}
				}
				container.addView(view);
//				mHolder.gifPicture.setOnClickListener(new OnClickListener() {
//					
//					@Override
//					public void onClick(View v) {
//						// TODO Auto-generated method stub
//						
//					}
//				});
				final GestureDetector detector=new GestureDetector(ShowImagesActivity.this, new GifSimpleOnGestureListener(mHolder.gifPicture));
				mHolder.gifPicture.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						return detector.onTouchEvent(event);
					}
				});
				view.findViewById(R.id.fragment_pic_layout).setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						return detector.onTouchEvent(event);
					}
				});
				return view;
//				ImageLoader.getInstance().displayImage(urlList.get(position), mHolder.ivPicture,
//						mChatImageOptions,
//						new SimpleImageLoadingListener() {
//							// PictureHolder savedHolder = map.get("" + pos);
//
//							@Override
//							public void onLoadingStarted(String imageUri, View view) {
//								if (mHolder != null) {
//									mHolder.registerEvent();
//									mHolder.listener.showProgress(100,
//											0,pos);
//								}
//							}
//
//							@Override
//							public void onLoadingCancelled(String imageUri, View view) {
//								if (mHolder != null) {
//									mHolder.listener.fail(pos);
//									mHolder.unRegisterEvent();
//								}
//							}
//
//							@Override
//							public void onLoadingComplete(String imageUri, View view,
//									Bitmap loadedImage) {
//								if (mHolder != null) {
//									mHolder.listener.success(pos);
//									mHolder.unRegisterEvent();
//								}
//							}
//
//							@Override
//							public void onLoadingProgress(long totalSize,
//									long downloadSize) {
//								if (mHolder != null) {
//									mHolder.listener.showProgress(totalSize,
//											downloadSize,pos);
//								}
//							}
//
//							@Override
//							public void onLoadingFailed(String imageUri, View view,
//									FailReason failReason) {
//								if (mHolder != null) {
//									mHolder.listener.fail(pos);
//									mHolder.unRegisterEvent();
//								}
//							}
//
//						});
				
			}
			
			@Override
			public void destroyItem(ViewGroup container, int position, Object object) {
				Log.i("showImagesActivity", "destroyItem " + position);
				View view = (View)object;
				PictureHolder mHolder = (PictureHolder) view.getTag();
				if (mHolder.gifPicture!=null){
					mHolder.gifPicture.quit();
				}
				mHolder.unRegisterEvent();
				container.removeView((View)object);
			}
			
			@Override
		    public Parcelable saveState() {
		        return null;
		    }
		});
		
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
            	Log.i("showImagesActivity", "onPageSelected " + position );
				currentPosition = position;
				tvPosition.setText((position + 1) + "/" + urlList.size());
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
	}
	
	@TargetApi(Build.VERSION_CODES.CUPCAKE)
	private class GifSimpleOnGestureListener extends SimpleOnGestureListener{
		public GifImageView mGifImageView;
		
		public GifSimpleOnGestureListener(GifImageView view){
			mGifImageView=view;
		}
		
		@TargetApi(Build.VERSION_CODES.CUPCAKE)
		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			ShowImagesActivity.this.finish();
			Log.d("debug","onSingleTapUp");
			return super.onSingleTapConfirmed(e);
		}
		
		@Override
		public boolean onDoubleTap(MotionEvent e) {
			Log.d("debug","onDoubleTap");
			mGifImageView.changeScale();
			return super.onDoubleTap(e);
		}
		
		@Override
		public boolean onDown(MotionEvent e) {
			//这里如果不返回TRUE,后面的事件不会被触发
			return true;
		}
	};
	
	private void doSave(int position) {
		//modify BUG #33412 by chenqsh 2014-1-21
		String url = urlList.get(position);
		if (TextHelper.isUrl(url)){
			new SaveTweetImageTask(url,null,this,ChatEntry.INSTANCE.chatOptions).execute();	
		}else{
			ToastUtils.display(this,getString(R.string.image_save_local_error,url));
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		//恢复动画
		if (viewPager!=null){
			View view=viewPager.getChildAt(0);
			if (view!=null){
				Object tag=view.getTag();
				if (tag!=null && tag instanceof PictureHolder){
					GifImageView gifPicture=((PictureHolder) tag).gifPicture;
					if (gifPicture!=null){
						gifPicture.startDecodeThread();
					}
				}	
			}
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		//停止动画
		if (viewPager!=null){
			int count=viewPager.getChildCount();
			for (int i=0;i<count;i++){
				View view=viewPager.getChildAt(i);
				Object tag=view.getTag();
				if (tag!=null && tag instanceof PictureHolder){
					GifImageView gifPicture=((PictureHolder) tag).gifPicture;
					if (gifPicture!=null){
						gifPicture.quit();
					}
				}
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		//回收图片
		if (mGifImageViews!=null){
			for(GifImageView view:mGifImageViews){
				view.recycle();
			}
		}
	}
}
